package com.speedy.course.ext

import android.view.View
import android.view.animation.AlphaAnimation
import android.view.animation.CycleInterpolator
import android.widget.CheckBox
import android.widget.EditText
import androidx.core.view.get
import androidx.core.widget.doOnTextChanged
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.bottomnavigation.BottomNavigationView
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow


/**
 * 显示view
 */
fun View?.visible() {
    this?.visibility = View.VISIBLE
}

/**
 * 显示view，带有渐显动画效果。
 *
 * @param duration 毫秒，动画持续时长，默认500毫秒。
 */
fun View?.visibleAlphaAnimation(duration: Long = 500L) {
    this?.visibility = View.VISIBLE
    this?.startAnimation(AlphaAnimation(0f, 1f).apply {
        this.duration = duration
        fillAfter = true
    })
}

/**
 * 隐藏view
 */
fun View?.gone() {
    this?.visibility = View.GONE
}

/**
 * view抖动动画
 */
fun View.shake(distance: Float, times: Int) {
    animate()
        .translationXBy(distance)
        .setInterpolator(CycleInterpolator(times.toFloat()))
        .setDuration(200L)
        .start()
}

fun EditText.inputFlow(): Flow<String?> {
    return callbackFlow {
        send(text?.toString())
        val textWatcher = doOnTextChanged { text, _, _, _ ->
            trySend(text?.toString())
        }
        awaitClose {
            removeTextChangedListener(textWatcher)
        }
    }
}

fun CheckBox.isCheckFlow(): Flow<Boolean> {
    return callbackFlow {
        send(isChecked)
        setOnCheckedChangeListener { _, isChecked -> trySend(isChecked) }
        awaitClose {
            setOnCheckedChangeListener(null)
        }
    }
}

private const val MENU_ORDER_MASK = 0x0000ffff

fun ViewPager2.setUpWithBottomNavigation(bottomNavigationView: BottomNavigationView) {
    registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            bottomNavigationView.menu.also {
                if (it.size() > position) {
                    it[position].isChecked = true
                }
            }
        }
    })
    bottomNavigationView.setOnItemSelectedListener {
        setCurrentItem(it.order and MENU_ORDER_MASK, false)
        true
    }
}

fun EditText.setTextAndSelectionIfNeed(content : CharSequence?) {
    if (text?.toString().orEmpty() != content?.toString().orEmpty()) {
        setText(content)
        setSelection(text?.length ?: 0)
    }
}